package com.tanhua.server.service;

import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.dubbo.api.db.UserApi;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 获取用户信息
 */
@Service
public class MessagesService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private FriendApi friendApi;

    /**
     * 通过环信id查询用户信息
     * @param huanxinId
     * @return
     */
    public UserInfoVo findUserByHuanxinUser(String huanxinId) {
        //1. 通过环信id查询用户
        User user = userApi.findByHuanxinUser(huanxinId);
        //2. 查询用户详情
        UserInfo userInfo = userInfoApi.findUserInfo(user.getId());
        //3. 转成vo
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, vo);
        vo.setAge(userInfo.getAge().toString());
        return vo;
    }

    /**
     * 添加好友
     * @return
     */
    public void addContacts(Long friendUserId) {
        User user = UserHolder.getUser();//当前用户信息
        //1.根据好友id 与  当前用户id 调用环信云 成为好友
        //参数1 参数2 都是环信用户名
        //1.1根据好友用户id获取tb_user对象
        User friendUser = userApi.findById(friendUserId);
        if(!huanXinTemplate.addContact(user.getHxUser(),friendUser.getHxUser())){
            throw new TanHuaException(ErrorResult.error());
        }
        //2. 根据好友id 与 当前用户id 调用服务保存好友关系（2条）
        friendApi.addContacts(friendUserId,user.getId());
    }

    /**
     * 联系人列表分页查询
     *  nickname like "%keyword%"
     * @return
     */
    public PageResult<ContactVo> findPageContacts(Long page, Long pageSize, String keyword) {
        Long userId = UserHolder.getUserId();
        //1根据当前用户id查询好友表
        PageResult<Friend> friendPageResult = friendApi.findPageContacts(page,pageSize,userId);
        if(CollectionUtils.isEmpty(friendPageResult.getItems())){
            return null;
        }
        //2获取所有的好友ids
        List<Friend> friendList = friendPageResult.getItems();
        List<Long> friendIdsList = friendList.stream().map(Friend::getFriendId).collect(Collectors.toList());
        //3根据所有好友ids查询tb_userInfo表
        UserInfo userInfoCondition  = new UserInfo();
        userInfoCondition.setNickname(keyword);
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(friendIdsList,userInfoCondition);
        //4.基于tb_userInfo构造Vo返回
        List<ContactVo> contactVoList = new ArrayList<>();
        for (Friend friend : friendList) {
            if(userInfoMap != null) {
                UserInfo userInfo = userInfoMap.get(friend.getFriendId());
                if (userInfo != null) {
                    contactVoList.add(ContactVo.init(userInfo));
                }
            }
        }
        return new PageResult<>(page,pageSize,friendPageResult.getCounts(),contactVoList);
    }
}
